package com.jt.www.biz.user_pc.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jt.www.biz.user_pc.service.IndustryManagerService;
import com.jt.www.dao.mapper.industry.IndustryManagerMapper;
import com.jt.www.domain.dto.IndustryManagerDto;
import com.jt.www.domain.enums.common.IndustryStatusEnum;
import com.jt.www.domain.enums.common.IsDeletedEnum;
import com.jt.www.domain.po.IndustryManager;
import com.jt.www.domain.qo.IndustryManagerQo;
import com.jt.www.domain.vo.IndustryManagerVo;
import com.jt.www.domain.vo.PhoneRegisterVO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.GenericResponse;
import com.jt.www.remote.UserClient;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by shaoyn on 2020/12/09.
 */
@Service
public class IndustryManagerServiceImpl implements IndustryManagerService {

    public static final Logger log = LoggerFactory.getLogger(IndustryManagerServiceImpl.class);
    @Autowired
    private IndustryManagerMapper industryManagerMapper;
    @Autowired
    private UserClient userClient;

    @Override
    public ResponseEntity addIndustryManager(String findCode, IndustryManagerVo industryManagerVo) {
        IndustryManager query = new IndustryManager();
        query.setAccount(industryManagerVo.getAccount());
        if (industryManagerMapper.selectCount(query) > 0) {
            return GenericDataResponse.errorWithMsg("该用户帐号已经被注册!");
        }

        //先做用户中心注册
        PhoneRegisterVO phoneRegisterVO = industryManagerVo.getPhoneRegisterVO();
        String userCode;
        try {
            log.info("{}调用用户中心注册入参：{}", findCode, JSON.toJSONString(phoneRegisterVO));
            GenericListResponse<PhoneRegisterVO> userResponse = userClient.registerByNameAndPhone(Lists.newArrayList(phoneRegisterVO));
            log.info("{}调用用户中心注册出参：{}", findCode, JSON.toJSONString(userResponse));
            if (GenericDataResponse.CODE_NG.equals(userResponse.getCode())
                    || CollectionUtils.isEmpty(userResponse.getList())) {
                return GenericDataResponse.errorWithMsg("注册失败!" + userResponse.getMsg());
            }
            userCode = userResponse.getList().get(0).getUserCode();
        } catch (Exception e) {
            log.info("{}调用用户中心注册异常{}", findCode, e.getMessage(), e);
            return GenericDataResponse.errorWithMsg("注册失败!" + e.getMessage());
        }

        IndustryManager industryManager = industryManagerVo.getIndustryManager();
        industryManager.setUserCode(userCode);
        industryManager.setCreateTime(new Date());
        industryManager.setStatus(IndustryStatusEnum.ENABLED.getStatus());
        industryManager.setIsDeleted(IsDeletedEnum.NO.getValue());
        int n = industryManagerMapper.insertSelective(industryManager);
        if (n == 1) {
            return GenericDataResponse.ok();
        }
        return GenericDataResponse.errorWithMsg("保存失败");
    }

    @Override
    public ResponseEntity updateIndustryManager(String findCode, IndustryManager industryManager) {
        industryManager.setStatus(null);
        industryManager.setUpdateTime(new Date());
        industryManagerMapper.updateByPrimaryKeySelective(industryManager);
        return GenericDataResponse.ok();
    }

    @Override
    public ResponseEntity<GenericListResponse<IndustryManagerDto>> queryIndustryManager(String findCode, IndustryManagerQo industryManagerQo) {
        List<IndustryManager> list1 = industryManagerMapper.queryIndustryManagerList(industryManagerQo);
        //转换
        List<IndustryManagerDto> list = Lists.transform(list1, industryManager -> new IndustryManagerDto(industryManager));
        log.info("{} 查询edu行管表出参：{}", findCode, JSON.toJSONString(list));
        return GenericListResponse.listNoCount(list);
    }

    @Override
    @Transactional
    public ResponseEntity updateIndustryManagerStatus(String findCode, Long id, Byte status) throws Exception {
        IndustryManager industryManager1 = industryManagerMapper.selectByPrimaryKey(id);
        if (null == industryManager1) {
            return GenericDataResponse.errorWithMsg("该用户状态异常!");
        }
        IndustryStatusEnum industryStatusEnum = IndustryStatusEnum.getEnumByValue(status);
        if (null == industryStatusEnum) {
            return GenericDataResponse.errorWithMsg("准备修改的状态不正确!");
        }
        if (status == industryManager1.getStatus()) {
            return GenericDataResponse.errorWithMsg("该用户状态已经是" + industryStatusEnum.getDesc() + ",不用修改!");
        }

        IndustryManager update = new IndustryManager();
        update.setId(id);
        update.setIsDeleted(IsDeletedEnum.NO.getValue());
        update.setStatus(status);
        update.setUpdateTime(new Date());
        int n = industryManagerMapper.updateByPrimaryKeySelective(update);
        if (n < 0) {
            return GenericDataResponse.errorWithMsg("修改失败!");
        }
        //修改用户中心
        GenericResponse response = userClient.loginLog(industryManager1.getUserCode(), String.valueOf(status));
        log.info("{} 修改用户中心状态出参:{}", findCode, JSON.toJSONString(response));
        if (GenericResponse.CODE_NG.equals(response.getCode())) {
            throw new RuntimeException(response.getMsg());
        }
        return GenericDataResponse.ok();
    }
}
